#!/usr/bin/env python3
"""快速同步最新内容到ES"""
from models import SessionLocal, Content, ContentTag, ContentMedia, User, Tag
from services.es_client import ESClient
import asyncio

async def sync_latest():
    db = SessionLocal()
    es_client = ESClient(use_async=False)
    
    try:
        # 获取最新的5条已发布内容
        contents = db.query(Content).filter(Content.status == 2).order_by(Content.id.desc()).limit(5).all()
        
        print(f"\n找到 {len(contents)} 条内容，开始同步到ES...\n")
        
        for content in contents:
            # 获取标签
            content_tags = db.query(ContentTag).filter(ContentTag.content_id == content.id).all()
            tag_ids = [ct.tag_id for ct in content_tags]
            
            if not tag_ids:
                print(f"跳过内容 {content.id} (无标签)")
                continue
            
            # 获取标签名称
            tags = db.query(Tag).filter(Tag.id.in_(tag_ids)).all()
            tag_names = [t.name for t in tags]
            
            # 获取首图
            first_media = db.query(ContentMedia).filter(
                ContentMedia.content_id == content.id
            ).order_by(ContentMedia.sort_order).first()
            
            # 获取作者
            author = db.query(User).filter(User.id == content.author_id).first()
            
            # 构建ES文档
            es_doc = {
                "content_id": content.id,
                "title": content.title,
                "description": content.description or "",
                "author_id": content.author_id,
                "author_nickname": author.nickname if author else "未知",
                "tag_ids": tag_ids,
                "tag_names": tag_names,
                "status": content.status,
                "view_count": content.view_count,
                "like_count": content.like_count,
                "comment_count": content.comment_count,
                "share_count": content.share_count,
                "collect_count": content.collect_count,
                "first_image_url": first_media.media_url if first_media else None,
                "media_urls": [first_media.media_url] if first_media else [],
                "media_types": [first_media.media_type] if first_media else [],
                "is_top": content.is_top,
                "created_at": content.created_at.isoformat() if content.created_at else None,
                "published_at": content.published_at.isoformat() if content.published_at else None
            }
            
            # 同步到ES
            try:
                await es_client.create_document(content.id, es_doc)
                print(f"OK: {content.id} - {content.title}")
            except Exception as e:
                print(f"FAIL: {content.id} - {str(e)}")
        
        print("\n同步完成！现在刷新前端页面应该能看到新内容了。")
        
    except Exception as e:
        print(f"ERROR: {e}")
    finally:
        db.close()

if __name__ == "__main__":
    asyncio.run(sync_latest())

